#include "UpdateLayer.h"

#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
#include <dirent.h>
#include <sys/stat.h>
#endif
using namespace std;

UpdateLayer::UpdateLayer(void)
{
}


UpdateLayer::~UpdateLayer(void)
{
	AssetsManager *pAssetsManager = getAssetsManager();
	CC_SAFE_DELETE(pAssetsManager);
}

bool UpdateLayer::init()
{
	CCLayer::init();

	createDownloadedDir();

	CCSize size = CCDirector::sharedDirector()->getWinSize();

	CCMenuItemFont* enterButton=CCMenuItemFont::create("Enter",this,menu_selector(UpdateLayer::enter));
	CCMenuItemFont* resetButton=CCMenuItemFont::create("Reset",this,menu_selector(UpdateLayer::reset));
	CCMenuItemFont* updateButton=CCMenuItemFont::create("Update",this,menu_selector(UpdateLayer::update));

	menu=CCMenu::create(enterButton,resetButton,updateButton,NULL);
	menu->alignItemsVerticallyWithPadding(30);
	this->addChild(menu);
	pProgressLabel = CCLabelTTF::create("", "Arial", 20);
	pProgressLabel->setPosition(ccp(100, 50));
	addChild(pProgressLabel);



	return true;
}

void UpdateLayer::onError( AssetsManager::ErrorCode errorCode )
{
	if (errorCode == AssetsManager::kNoNewVersion)
	{
		pProgressLabel->setString("no new version");
	}

	if (errorCode == AssetsManager::kNetwork)
	{
		pProgressLabel->setString("network error");
	}
}

void UpdateLayer::onProgress( int percent )
{
	char progress[20];
	snprintf(progress, 20, "downloading %d%%", percent);
	pProgressLabel->setString(progress);
}

void UpdateLayer::onSuccess()
{
	pProgressLabel->setString("download ok");
}

void UpdateLayer::createDownloadedDir()
{
	pathToSave = CCFileUtils::sharedFileUtils()->getWritablePath();
	pathToSave += "tmpdir";

	// Create the folder if it doesn't exist
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
	DIR *pDir = NULL;

	pDir = opendir (pathToSave.c_str());
	if (! pDir)
	{
		mkdir(pathToSave.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
	}
#else
	if ((GetFileAttributesA(pathToSave.c_str())) == INVALID_FILE_ATTRIBUTES)
	{
		CreateDirectoryA(pathToSave.c_str(), 0);
	}
#endif
}

cocos2d::extension::AssetsManager* UpdateLayer::getAssetsManager()
{
	    static AssetsManager *pAssetsManager = NULL;
    
    if (! pAssetsManager)
    {
		pAssetsManager = new AssetsManager("http://127.0.0.1/package.zip",
			"https://raw.github.com/minggo/AssetsManagerTest/master/version",
			pathToSave.c_str());
        pAssetsManager->setDelegate(this);
        pAssetsManager->setConnectionTimeout(3);
    }
    
    return pAssetsManager;
}

void UpdateLayer::enter( CCObject* pSender )
{
	if (! isUpdateItemClicked)
	{
		vector<string> searchPaths = CCFileUtils::sharedFileUtils()->getSearchPaths();
		searchPaths.insert(searchPaths.begin(), pathToSave);
		CCFileUtils::sharedFileUtils()->setSearchPaths(searchPaths);
	}
	this->addChild(CCSprite::create("Background.png"),0);
}

void UpdateLayer::reset( CCObject* pSender )
{
	pProgressLabel->setString(" ");

	// Remove downloaded files
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32)
	string command = "rm -r ";
	// Path may include space.
	command += "\"" + pathToSave + "\"";
	system(command.c_str());
#else
	string command = "rd /s /q ";
	// Path may include space.
	command += "\"" + pathToSave + "\"";
	system(command.c_str());
#endif
	// Delete recorded version codes.
	getAssetsManager()->deleteVersion();

	createDownloadedDir();
}

void UpdateLayer::update( CCObject* pSender )
{
	pProgressLabel->setString("");

	// update resources
	getAssetsManager()->update();

	isUpdateItemClicked = true;
}
